package logic

import (
	"context"
	"fmt"
	"hr_srv/models"

	"hr_srv/hr_srv"
	"hr_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *hr_srv.LoginRequest) (*hr_srv.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	rest := false
	if in.Code == 0 {
		key := in.Phone
		get, _ := models.RDB.Get(models.Ctx, key).Result()
		if get != in.Captcha {
			return &hr_srv.LoginResponse{}, fmt.Errorf("验证码错误")
		}
		if models.DB.Where("phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
			return &hr_srv.LoginResponse{}, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			if models.DB.Create(&models.User{Phone: in.Phone}).Error != nil {
				return &hr_srv.LoginResponse{}, fmt.Errorf("服务器繁忙")
			}
			if models.DB.Where("phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
				return &hr_srv.LoginResponse{}, fmt.Errorf("服务器繁忙")
			}
			rest = true
		}
	} else {
		if models.DB.Where("phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
			return &hr_srv.LoginResponse{}, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return &hr_srv.LoginResponse{}, fmt.Errorf("账号未注册")
		}
		if user.Password != in.Password {
			return &hr_srv.LoginResponse{}, fmt.Errorf("账号或密码错误")
		}
	}
	if rest {
		return &hr_srv.LoginResponse{
			Code:   1,
			UserId: int64(user.ID),
		}, nil
	} else {
		return &hr_srv.LoginResponse{
			Code:   0,
			UserId: int64(user.ID),
		}, nil
	}
}
